<template>
  <div class="app-container">
    <div class="" style="width:100%;padding:10px;height:50px">
      <el-button size="mini" type="primary" style="float:left" @click="handleCreate()">新增</el-button>
      <el-upload
        class="upload-demo"
        :action="getUpload()"
        :headers="getHeaders()"
        :file-list="fileList"
        :on-success="setPage"
        style="float:left"
        multiple>
        <el-button size="mini" type="primary" style="float:left;margin-left: 10px;">点击上传</el-button>
        <div class="el-upload__tip" slot="tip" style="float:right;margin-left: 10px;margin-right: 10px;">只能上传xlsx文件，且不超过5MB</div>
      </el-upload>
      <!--<el-button size="mini" type="primary" style="float:left" @click="handleCreate()">Excel导入</el-button>-->
      <el-button size="mini" type="primary" style="float:left" @click="handleDownload()">导入模板下载</el-button>
      <el-button
        size="mini"
        type="primary"
        style="float: right; margin-left: 10px"
        icon="el-icon-search"
        @click="handleFilter"
        >搜索
      </el-button>
      <el-input
            v-model="listQuery.userName_LIKE"
            autocomplete="off"
            placeholder="请输入用户名称"
        style="float: right; width: 150px;margin-left: 5px;"
          />
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :header-cell-style="{'background-color': '#F5F8FB'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column align="center" label="序号" type="index" :index="indexMethod" />
      <!--<el-table-column align="center" label="用户ID">
        <template slot-scope="scope">
          <span :title="scope.row.userId">{{ scope.row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="企业ID">
        <template slot-scope="scope">
          <span :title="scope.row.businessId">{{ scope.row.businessId }}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="用户名称">
        <template slot-scope="scope">
          <span :title="scope.row.userName">{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名">
        <template slot-scope="scope">
          <span :title="scope.row.name">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号">
        <template slot-scope="scope">
          <span :title="scope.row.phone">{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="邮箱">
        <template slot-scope="scope">
          <span :title="scope.row.email">{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="盐">
        <template slot-scope="scope">
          <span :title="scope.row.salt">{{ scope.row.salt }}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="上次登录时间">
        <template slot-scope="scope">
          <span :title="scope.row.datetime">{{ scope.row.datetime }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="密码（加密后）">
        <template slot-scope="scope">
          <span :title="scope.row.password">{{ scope.row.password }}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <span :title="scope.row.status==0?'启用':'禁用'">{{ scope.row.status==0?'启用':'禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型">
        <template slot-scope="scope">
          <span :title="scope.row.type ==0?'普通用户':'管理员'">{{ scope.row.type ==0?'普通用户':'管理员'}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="创建人">
        <template slot-scope="scope">
          <span :title="scope.row.createId">{{ scope.row.createId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span :title="scope.row.createTime">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新人">
        <template slot-scope="scope">
          <span :title="scope.row.updateId">{{ scope.row.updateId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间">
        <template slot-scope="scope">
          <span :title="scope.row.updateTime">{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="删除状态(0-正常,1-已删除)">
        <template slot-scope="scope">
          <span :title="scope.row.delFlag">{{ scope.row.delFlag }}</span>
        </template>
      </el-table-column>-->
      <el-table-column fixed="right" align="center" label="操作" class-name="small-padding fixed-width" width="300px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="success" @click="handleEnable(scope.row)" v-show="scope.row.status!=0">启用</el-button>
          <el-button size="mini" type="warning" @click="handleDisable(scope.row)" v-show="scope.row.status==0">禁用</el-button>
          <el-button size="mini" type="info" @click="handleAuth(scope.row)">授权</el-button>
          <el-button size="mini" type="warning" @click="handleReset(scope.row)">重置密码</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]"
        :page-size="listQuery.limit"
        :total="total"
        background
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="用户维护" :visible.sync="dialogVisible">
      <el-form ref="userForm" :model="user" :rules="rules" size="mini">
        <!--<el-form-item label="用户ID" prop="userId" :label-width="formLabelWidth">
          <el-input v-model="user.userId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="企业ID" prop="businessId" :label-width="formLabelWidth">
          <el-input v-model="user.businessId" autocomplete="off" />
        </el-form-item>-->
        <el-form-item label="登录名" prop="userName" :label-width="formLabelWidth">
          <el-input v-model="user.userName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="user.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone" :label-width="formLabelWidth">
          <el-input v-model="user.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="user.email" autocomplete="off" />
        </el-form-item>
        <!--<el-form-item label="盐" prop="salt" :label-width="formLabelWidth">
          <el-input v-model="user.salt" autocomplete="off" />
        </el-form-item>
        <el-form-item label="上次登录时间" prop="datetime" :label-width="formLabelWidth">
          <el-input v-model="user.datetime" autocomplete="off" />
        </el-form-item>-->
        <el-form-item label="密码" prop="pw" :label-width="formLabelWidth">
          <el-input v-model="user.pw" autocomplete="off" />
        </el-form-item>
        <!--<el-form-item label="状态" prop="status" :label-width="formLabelWidth">
          <el-input v-model="user.status" autocomplete="off" />
        </el-form-item>-->
        <el-form-item label="类型" prop="type" :label-width="formLabelWidth">
          <!--<el-input v-model="user.type" autocomplete="off" />-->
          <el-radio-group v-model="user.type">
            <el-radio :label="0">普通用户</el-radio>
            <el-radio :label="1">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--<el-form-item label="创建人" prop="createId" :label-width="formLabelWidth">
          <el-input v-model="user.createId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime" :label-width="formLabelWidth">
          <el-input v-model="user.createTime" autocomplete="off" />
        </el-form-item>
        <el-form-item label="更新人" prop="updateId" :label-width="formLabelWidth">
          <el-input v-model="user.updateId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime" :label-width="formLabelWidth">
          <el-input v-model="user.updateTime" autocomplete="off" />
        </el-form-item>
        <el-form-item label="删除状态(0-正常,1-已删除)" prop="delFlag" :label-width="formLabelWidth">
          <el-input v-model="user.delFlag" autocomplete="off" />
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSaveOrUpdate()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="授权管理" :visible.sync="authVisible">
      <el-form ref="authForm" size="mini">
        <el-checkbox-group v-model="checkList">
          <div v-for="(system, index) in groupList">
            <h3 style="font-size: 16px;">{{ system.systemName }}</h3>
            <el-checkbox v-for="(group, index) in system.group" :label="group.groupId" :key="group.groupId">{{group.groupName }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="authVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleSaveUser()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { del, get, getPage, save, update,enable,disable ,resetPassword,getUploadUrl} from '@/api/User'

import { getDownloadUrl } from '@/api/Common'

import { getGroup } from '@/api/Group'

import { saveUser } from '@/api/Relation'

const sha256 = require("js-sha256").sha256;

export default {
  data() {
    return {
      total: null,
      list: null,
      listLoading: true,
      dialogVisible: false,
      authVisible: false,
      fileList:[],
      listQuery: {
        page: 1,
        size: 10
      },
      checkList:[],
      groupList:[],
      user: {
        userId: null,
        businessId: null,
        userName: null,
        phone: null,
        email: null,
        salt: null,
        datetime: null,
        password: null,
        status: 0,
        type: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null,
        delFlag: null,
        pw:null
      },
      userCopy: null,
      rules: {
        userId: [{ required: true, message: '请填写用户ID', trigger: 'blur' }],
        businessId: [{ required: true, message: '请填写企业ID', trigger: 'blur' }],
        userName: [{ required: true, message: '请填写用户名称', trigger: 'blur' }],
        name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写手机号', trigger: 'blur' }],
        email: [{ required: true, message: '请填写邮箱', trigger: 'blur' }],
        salt: [{ required: true, message: '请填写盐', trigger: 'blur' }],
        datetime: [{ required: true, message: '请填写上次登录时间', trigger: 'blur' }],
        password: [{ required: true, message: '请填写密码（加密后）', trigger: 'blur' }],
        pw: [{ required: true, message: '请填写初始密码', trigger: 'blur' }],
        status: [{ required: true, message: '请填写状态', trigger: 'blur' }],
        type: [{ required: true, message: '请填写类型', trigger: 'blur' }],
        createId: [{ required: true, message: '请填写创建人', trigger: 'blur' }],
        createTime: [{ required: true, message: '请填写创建时间', trigger: 'blur' }],
        updateId: [{ required: true, message: '请填写更新人', trigger: 'blur' }],
        updateTime: [{ required: true, message: '请填写更新时间', trigger: 'blur' }],
        delFlag: [{ required: true, message: '请填写删除状态(0-正常,1-已删除)', trigger: 'blur' }],
      },
      formLabelWidth: '120px'
    }
  },
  created() {
    this.getPage()
  },
  methods: {
    getHeaders(){
      var headers = {'Authorization':localStorage.getItem('access_token')};
      return headers;
    },
    getUpload(){
      return getUploadUrl();
    },
    setPage(res,file){
      if(res.code===200){
        this.getPage();
        this.fileList = []
      }else{
        this.$message({
          type: 'danger',
          message: '上传失败，'+res.msg
        })
      }
    },
    handleDownload(){
      getDownloadUrl({fileName: "userImport.xlsx"}).then(response => {
        let url = window.URL.createObjectURL(new Blob([response]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', "userImport.xlsx");
        document.body.appendChild(link);
        link.click();
      })
    },
    getPage() {
      this.listLoading = true
      getPage(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getPage()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getPage()
    },
    indexMethod(index) {
      return this.listQuery.size * (this.listQuery.page - 1) + index + 1
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getPage()
    },
    handleCreate() {
      Object.keys(this.user).forEach(key => (this.user[key] = null))
      this.userCopy = null
      this.dialogVisible = true
      if (this.$refs['userForm'] !== undefined) {
        this.$refs['userForm'].clearValidate()
      }
    },
    handleEdit(row) {
      const params = { id: row.userId }
      get(params).then(response => {
        this.user = response.data
        this.userCopy = response.data
      })
      this.dialogVisible = true
      if (this.$refs['userForm'] !== undefined) {
        this.$refs['userForm'].clearValidate()
      }
    },
    handleAuth(row) {
      const params = { id: row.userId }
      get(params).then(response => {
        this.user = response.data
        this.userCopy = response.data
      })
      getGroup(row.userId).then(response => {
        this.groupList = response.data.system
        this.checkList = response.data.check
      })
      this.authVisible = true;
    },
    randomString(len) {
　　  len = len || 32;
　　  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
　　  var maxPos = $chars.length;
　　  var pwd = '';
　　  for (var i = 0; i < len; i++) {
　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
　　  }
　　  return pwd;
    },
    handleReset(row) {
      this.$confirm('是否重置该用户密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var newPw = this.randomString(8);
        row.userName = sha256(newPw),
        resetPassword(row).then(() => {
          this.$message({
            type: 'success',
            message: '重置成功，新密码为' + newPw,
            showClose: true,
            duration:0,
          })
          this.getPage()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消重置'
        })
      })
    },
    handleEnable(row) {
      this.$confirm('是否启用该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enable(row.userId).then(() => {
          this.$message({
            type: 'success',
            message: '启用成功'
          })
          this.getPage()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消启用'
        })
      })
    },
    handleDisable(row) {
      this.$confirm('是否禁用该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disable(row.userId).then(() => {
          this.$message({
            type: 'success',
            message: '禁用成功'
          })
          this.getPage()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消禁用'
        })
      })
    },
    handleDelete(row) {
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row.userId).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getPage()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    handleSaveOrUpdate() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          if (this.user.userId) {
            update(this.user).then(() => {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
              this.dialogVisible = false
              this.getPage()
            })
          } else {

            this.user.password = sha256(this.user.pw)

            save(this.user).then(() => {
              this.$message({
                type: 'success',
                message: '保存成功'
              })
              this.dialogVisible = false
              this.getPage()
            })
          }
        } else {
          this.$message.error('请保证数据填写正确！')
        }
      })
    },
    handleSaveUser(){
          var system = {businessId:this.user.businessId,systemId:0,userId:this.user.userId,checkList:this.checkList}
          saveUser(system).then(() => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.authVisible = false
            this.getPage()
          })
    }
  }
}
</script>

<style>
.el-input__icon {
  line-height: 30px;
}
.el-input__inner {
  height: 30px;
  line-height: 30px;
}
</style>
